package com.lwx.sys.controller;

import com.lwx.sys.domain.Loginfo;
import com.lwx.sys.domain.User;
import com.lwx.sys.service.LoginfoService;
import com.lwx.sys.utils.ActiveUser;
import com.lwx.sys.utils.BufferImageUtil;
import com.lwx.sys.utils.ResultObj;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private LoginfoService loginfoService;
    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    /**
     * 通过shiro验证登录信息是否正确
     * @param username
     * @param password
     * @param code
     * @param httpSession
     * @param request
     * @return
     */
    @PostMapping("/login")
    public ResultObj login(String username, String password, String code, HttpSession httpSession, HttpServletRequest request) {
        try {
            //判断验证码
            if (StringUtils.isNotEmpty(code) && !StringUtils.equals(code, (String) redisTemplate.opsForValue().get("imgcode"))) {
                return ResultObj.LOGIN_ERROR;
            }
            //使用shiro，登录
            //获取shiro当前操作用户
            Subject subject = SecurityUtils.getSubject();
            //封装用户的登录信息
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
            //执行登录方法
            subject.login(usernamePasswordToken);
            //获得用户
            ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
            //把用户放入session
            User user = activeUser.getUser();
            httpSession.setAttribute("userId", user.getId());
            httpSession.setAttribute("userName", user.getName());
            //写入登录日志
            Loginfo loginfo = new Loginfo();
            loginfo.setLoginname(user.getName());
            //获取ip
            loginfo.setLoginip(request.getRemoteAddr());
            loginfo.setLogintime(new Date());
            loginfoService.save(loginfo);

            return ResultObj.LOGIN_SUCESS;
        } catch (Exception e) {
            return ResultObj.LOGIN_ERROR;
        }
    }

    /**
     * 图片验证码
     *
     * @param res 响应对象
     * @throws IOException
     */
    @GetMapping(value = "/BufferImage")
    protected void createImg(HttpServletResponse res) throws IOException {
        //1.生成随机的验证码及图片
        Object[] objs = BufferImageUtil.createImage();
        //2.将验证码存入redis
        String imgcode = (String) objs[0];
        redisTemplate.opsForValue().set("imgcode", imgcode);
        redisTemplate.expire("imgcode", 5, TimeUnit.MINUTES);
        //3.将图片输出给浏览器
        BufferedImage img = (BufferedImage) objs[1];
        res.setContentType("image/png");
        //服务器自动创建输出流，目标指向浏览器
        OutputStream os = res.getOutputStream();
        ImageIO.write(img, "png", os);
        os.close();
    }
}
